#include "sylar/sylar.h"
#include "sylar/iomanager.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <sys/epoll.h>

sylar::Logger::ptr g_logger = SYLAR_LOG_ROOT();

int sock = 0;

void watch_io_read();

// 写事件回调，只执行一次，用于判断非阻塞套接字connect成功
void do_io_write() {
  SYLAR_LOG_INFO(g_logger) << "write callback";
  int so_err = 0;
  socklen_t len = size_t(so_err);
  getsockopt(sock, SOL_SOCKET, SO_ERROR, &so_err, &len);
  if(so_err) {
    SYLAR_LOG_INFO(g_logger) << "connect fail";
    return;
  }
  SYLAR_LOG_INFO(g_logger) << "connect success";
  std::string s = "GET /index.html HTTP/1.1/r/n"
                  "Host: www.baidu.com/r/n/r/n";
  SYLAR_LOG_INFO(g_logger) << "s:  " << s.c_str();
  int rt = 0;
  while(rt <= s.size()) {
    rt += write(sock, s.c_str() + rt, sizeof(s.size()) - rt);
    SYLAR_LOG_INFO(g_logger) << "write size: " << rt;
  }

  if (rt == 0) {
    SYLAR_LOG_INFO(g_logger) << "write fail";
  } else {
    SYLAR_LOG_INFO(g_logger) << "write size: " << rt;
  }
}

// 读事件回调，每次读取之后如果套接字未关闭，需要重新添加
void do_io_read() {
  SYLAR_LOG_INFO(g_logger) << "read callback";
  char buf[1024] = {0};
  int readlen = 0;
  readlen = read(sock, buf, sizeof(buf));
  if(readlen > 0) {
    buf[readlen] = '\0';
    SYLAR_LOG_INFO(g_logger) << "read " << readlen << " bytes, read: " << buf;
  } else if(readlen == 0) {
    SYLAR_LOG_INFO(g_logger) << "peer closed";
    close(sock);
    return;
  } else {
    SYLAR_LOG_ERROR(g_logger) << "err, errno=" << errno << ", errstr=" << strerror(errno);
    close(sock);
    return;
  }
  // read之后重新添加读事件回调，这里不能直接调用addEvent，因为在当前位置fd的读事件上下文还是有效的，直接调用addEvent相当于重复添加相同事件
  sylar::IOManager::GetThis()->schedule(watch_io_read);
}

void test_fiber() {
  SYLAR_LOG_INFO(g_logger) << "test_fiber sock = " << sock;
  sock = socket(AF_INET, SOCK_STREAM, 0);
  fcntl(sock, F_SETFL, O_NONBLOCK);

  sockaddr_in addr;
  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;
  addr.sin_port = htons(80);
  inet_pton(AF_INET, "110.242.68.3", &addr.sin_addr.s_addr);
/*
  while(connect(sock, (const sockaddr*)&addr, sizeof(addr))) ;
  sylar::IOManager::GetThis()->addEvent(sock, sylar::IOManager::READ, do_io_read);
  sylar::IOManager::GetThis()->addEvent(sock, sylar::IOManager::WRITE, do_io_write);
*/

  if(!connect(sock, (const sockaddr*)&addr, sizeof(addr))) {
  } else if(errno == EINPROGRESS) {
    SYLAR_LOG_INFO(g_logger) << "add event errno=" << errno << " " << strerror(errno);
    sylar::IOManager::GetThis()->addEvent(sock, sylar::IOManager::READ, do_io_read);
    sylar::IOManager::GetThis()->addEvent(sock, sylar::IOManager::WRITE, do_io_write);
  } else {
    SYLAR_LOG_INFO(g_logger) << "else " << errno << " " << strerror(errno);
  }
  // SYLAR_LOG_INFO(g_logger) << "connection "
}

void watch_io_read() {
  SYLAR_LOG_INFO(g_logger) << "watch_io_read";
  sylar::IOManager::GetThis()->addEvent(sock, sylar::IOManager::READ, do_io_read);
}

void test1() {
  std::cout << "EPOLLIN=" << EPOLLIN
            << " EPOLLOUT=" << EPOLLOUT << std::endl;
  sylar::IOManager iom(2, false);
  iom.schedule(&test_fiber);
}

sylar::Timer::ptr s_timer;
void test_timer() {
  sylar::IOManager iom(2);
  s_timer = iom.addTimer(1000, [](){
    static int i = 0;
    SYLAR_LOG_INFO(g_logger) << "hello timer i=" << i;
    if(++i == 3) {
      s_timer->reset(2000, true);
      //s_timer->cancel();
    }
  }, true);
}



int main(int argc, char** argv) {
  test1();
  // test_timer();
  return 0;
}